package br.com.educa.json;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Date;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;

@Aspect
public class ObjectToJson {

	@Around("call(flexjson.JSONSerializer.new(..))")
	public Object dateFormatter(ProceedingJoinPoint pjp) throws Throwable {

		Object object = pjp.proceed();
		JSONSerializer serializer = (JSONSerializer) object;
		serializer.transform(new DateTransformer("dd/MM/yyyy"), Date.class);
		return serializer;
	}

	@Around("execution(public * br.com.educa..toJson(..))")
	public Object collectionIncludes(ProceedingJoinPoint pjp) throws Throwable {

		Object target = pjp.getThis();
		Field[] fields = target.getClass().getDeclaredFields();

		JSONSerializer serializer = new JSONSerializer().exclude("*.class");
		serializer.transform(new DateTransformer("dd/MM/yyyy"), Date.class);
		for (Field field : fields) {
			Annotation[] annotations = field.getAnnotations();
			for (Annotation annotation : annotations) {
				if(annotation.toString().contains("javax.persistence.OneToMany") ||annotation.toString().contains("javax.persistence.ElementCollection") ||annotation.toString().contains("javax.persistence.ManyToMany") ){
					serializer.include(field.getName());
					System.out.println("serializer.include("+field.getName()+");");
				}
			}
		}
		String retorno = serializer.serialize(target);
		return retorno;

	}

}